package cn.gov.cus.rmftquartz.mappers.oracle.provider;

import cn.gov.cus.rmftquartz.entity.RmftHitResultVo;
import com.google.common.base.Strings;
import org.apache.ibatis.jdbc.SQL;

/**
 * @author wxming.
 * @date 2018/3/9.
 */
public class ManifestHitProvider {

    public String doSearchRule(RmftHitResultVo manifestHitVo){
        SQL sql = new SQL().SELECT("RULE_ID ruleHit,START_DATE startDate,REAL_END_DATE endDate").FROM("RULE");
        sql.WHERE("1=1");

        String ruleTypeAlias = manifestHitVo.getRuleTypeAlias();
        if(!Strings.isNullOrEmpty(ruleTypeAlias)){
            sql.WHERE(" RULE_ID like"+"\'"+ruleTypeAlias+"%"+"\'");
        }
        String ruleHit = manifestHitVo.getRuleHit();
        if(!Strings.isNullOrEmpty(ruleHit)){
            sql.WHERE(" RULE_ID like '%'||#{ruleHit}||'%'");//防止SQl注入的写法。#预编译。
        }
        String IEType = manifestHitVo.getIEType();
        if(!Strings.isNullOrEmpty(IEType)){
            sql.WHERE(" I_E_TYPE ="+"\'"+IEType+"\'");
        }
        String begin = manifestHitVo.getBegin();
        String end = manifestHitVo.getEnd();
        if(!Strings.isNullOrEmpty(begin) && !Strings.isNullOrEmpty(end)){
            sql.WHERE(" ((TO_CHAR(START_DATE,'yyyy-MM-dd HH:mm:ss') >= \'"+begin+"\' and TO_CHAR(START_DATE,'yyyy-MM-dd HH:mm:ss') <= \'" +end +"\') or (TO_CHAR(REAL_END_DATE,'yyyy-MM-dd HH:mm:ss') >= \'"+begin+"\' and TO_CHAR(REAL_END_DATE,'yyyy-MM-dd HH:mm:ss') <= \'"+end+"\') or (TO_CHAR(START_DATE,'yyyy-MM-dd HH:mm:ss') <= \'"+begin+"\' and TO_CHAR(REAL_END_DATE,'yyyy-MM-dd HH:mm:ss') >= \'"+end+"\') or (REAL_END_DATE id null and TO_CHAR(START_DATE,'yyyy-MM-dd HH:mm:ss')< \'"+begin+"\'))");
        }else if(!Strings.isNullOrEmpty(begin)){
            sql.WHERE(" (TO_CHAR(REAL_END_DATE,'yyyy-MM-dd HH:mm:ss') >= "+"\'"+begin+"\' or REAL_END_DATE is null )");
        }else if(!Strings.isNullOrEmpty(end)){
            sql.WHERE("TO_CHAR(START_DATE,'yyyy-MM-dd HH:mm:ss') <= "+"\'"+end+"\'");
        }

        sql.ORDER_BY("START_DATE DESC,RULE_ID ASC");
        return sql.toString();

    }
}
